import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import type { StrategyOptions } from 'passport-jwt';
import {
  HttpException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  // 这里的 Strategy 必须是 passport-jwt 包中的
  constructor(private readonly configService: ConfigService) {
    super({
      // debug: true, // <--- 添加调试选项
      // jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      jwtFromRequest: (req: any) => this.extractTokenFromRequest(req),
      secretOrKey: configService.get('JWT_SECRET') ?? 'secret',
    } as StrategyOptions);
  }
  // 自定义 token 提取方法
  private extractTokenFromRequest(req: any): string | null {
    // 自定义提取 token 的逻辑，这里我们从请求头中提取 shortToken
    const shortToken = req.headers['token'] || null;
    console.log('shortToken   --', shortToken);
    return shortToken;
  }

  async validate(payload: any) {
    console.log('payload   --', payload);
    if (!payload.sub) throw new HttpException('token没有关键字~', 444);
    // let existUser = await this.redisService.getValues_halh({
    //   key: this.globalService._redisHeadLoginStateHash,
    //   nestedKey: payload.sub + '',
    //   st: true,
    // });
    // if (!existUser) throw new UnauthorizedException('token用户不存在~');
    // //写入token信息进
    // return existUser;
    return { myInfo: payload };
  }
}
